package com.lin.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lin.shiro.JWTToken;
import com.lin.utils.LinResult;
import org.apache.commons.lang.CharEncoding;
import org.apache.http.HttpStatus;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @author 霖霖
 * @version 1.0
 * @date 2023/3/29 9:00
 * @Description 认证过滤器
 */
public class JWTFilter extends BasicHttpAuthenticationFilter {
    private String errorMessage;

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {

        HttpServletRequest httpServletRequest = (HttpServletRequest) request;

        String token = httpServletRequest.getHeader("Authorization");
        String loginType=httpServletRequest.getHeader("LoginType");
        try{
            SecurityUtils.getSubject().login(new JWTToken(token,loginType));
            return true;
        }catch (UnauthenticatedException | AuthenticationException unauthenticatedException){
            errorMessage=unauthenticatedException.getMessage();
            return false;
        }
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;

        httpServletResponse.setStatus(HttpStatus.SC_UNAUTHORIZED);
        httpServletResponse.setCharacterEncoding(CharEncoding.UTF_8);
        httpServletResponse.setContentType("application/json;charset=utf-8");
        PrintWriter writer = httpServletResponse.getWriter();
        ObjectMapper objectMapper = new ObjectMapper();
        writer.println(objectMapper.writeValueAsString(LinResult.error().code(HttpStatus.SC_UNAUTHORIZED).message(errorMessage)));
        writer.flush();
        writer.close();
        return false;

    }

    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest req=(HttpServletRequest) request;
        HttpServletResponse resp=(HttpServletResponse) response;
        if (req.getMethod().equals(RequestMethod.OPTIONS.name())){
            setCORSHeader(req,resp);
            return true;
        }
        setCORSHeader(req,resp);
        return super.preHandle(request, response);

    }

    private void setCORSHeader(HttpServletRequest request, HttpServletResponse response) {
        //跨域的header设置
        response.setHeader("Access-control-Allow-Origin", request.getHeader("Origin"));
        response.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Headers", request.getHeader("Access-Control-Request-Headers"));
        //防止乱码，适用于传输JSON数据
        response.setHeader("Content-Type","application/json;charset=UTF-8");
        response.setStatus(org.springframework.http.HttpStatus.OK.value());
    }

}
